<?php

namespace app\common\cachemodel\wecaht;

use app\common\model\BaseCache;
use XznsTools\cache\CacheManage;

class WechatLingqianCompleteRecord extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.wechat_lingqian_complete_record';

    protected $cacheModel = 'wechat_h5.user_cards';

    /**
     * 获取 本月 凑齐数量信息
     * @return array
     * @throws \Exception
     */
    public function getCompleteData()
    {
        $month = date('Ym');
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('card_complete', $month)->getDataAndSet(function () use ($month)
        {
            $monthTime = strtotime($month . '01');
            $data = $this->where(['create_time' => ['>', $monthTime]])->field('uid,type')->select();

            $resData = [
                1 => [ // 1=>女王卡
                    'num' => 0,
                    'uids' => [],
                ],
                2 => [ // 2=>凑齐50张卡
                    'num' => 0,
                    'uids' => [],
                ],
            ];

            foreach ($data as $datum)
            {
                $type = (int)$datum['type'];
                $resData[$type]['num'] += 1;
                $resData[$type]['uids'][] = (int)$datum['uid'];
            }

            foreach ($resData as $k => $datum)
            {
                $resData[$k] = json_encode($datum, JSON_UNESCAPED_UNICODE);
            }
            return $resData;
        }, [], 'card_complete');

        foreach ($data as $k => $datum)
        {   // $k => 1=>女王卡  2=>凑齐50张卡
            $data[$k] = json_decode($datum, true);
        }

        return $data;
    }

    /**
     * 获取 本月 可凑齐 日期
     * @param int $dayNum 可凑齐 日期天数
     * @return array
     * @throws \Exception
     */
    public function getCompleteWinDate(int $dayNum)
    {
        $month = date('Ym');
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('card_complete_win_date', $month)
            ->setCacheType('string')->getDataAndSet(function () use ($dayNum)
            {
                if ($dayNum > 0)
                {
                    $day = (int)date('d');
                    $numbers = range($day, date('t'));
                    shuffle($numbers); // 打乱数组顺序
                    $result = array_slice($numbers, 0, $dayNum); // 取前n个数
                    return json_encode($result, JSON_UNESCAPED_UNICODE);
                } else
                {
                    return json_encode([], JSON_UNESCAPED_UNICODE);
                }
            }, [], 'card_complete_win_date');

        return $data ? json_decode($data, true) : [];
    }
}